is_a
檢查對像是否屬於此類,或者將此類作為其父類之一: 如果對象屬於該類或該類是此對象的父類則返回true
函數名:is_a()
適用版本:PHP 4, PHP 5, PHP 7
用法:is_a() 函數用於檢查一個對像是否屬於指定的類或其子類。
語法:bool is_a( object $object, string $class_name )
參數:
返回值:
示例:
class Person { public $name; } class Student extends Person { public $grade; } $person = new Person(); $student = new Student(); // 检查$person 是否是Person 类的对象if (is_a($person, 'Person')) { echo '$person 是Person 类的对象'; } else { echo '$person 不是Person 类的对象'; } // 检查$student 是否是Person 类的对象if (is_a($student, 'Person')) { echo '$student 是Person 类的对象'; } else { echo '$student 不是Person 类的对象'; } // 检查$student 是否是Student 类的对象if (is_a($student, 'Student')) { echo '$student 是Student 类的对象'; } else { echo '$student 不是Student 类的对象'; }
輸出:
$person 是Person 类的对象$student 是Person 类的对象$student 是Student 类的对象
以上示例中,我們定義了一個Person 類和一個Student 類,Student 類是Person 類的子類。我們創建了一個$person 對象和一個$student 對象。使用is_a() 函數來檢查這些對象的類屬關係。第一個檢查表明$person 是Person 類的對象,第二個檢查表明$student 也是Person 類的對象,第三個檢查表明$student 是Student 類的對象。